<?php
namespace App\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Redis;
use App\Librarys\Wechatcrypts\Wxbizmsgcrypt;
use Log,Exception,Config;

class WechatopenService
{
    public static function openClicent($request)
    {
        $component_appid = $request->component_appid;
        $config = Config::get("wechats.component_platform.".$component_appid);
        $wxcpt = new WXBizMsgCrypt($config["token"],$config["aes_key"],$component_appid);
        $sPostData = $request->getcontent();
        $message = "";
        $errCode = $wxcpt->DecryptMsg($request->msg_signature, $request->timestamp, $request->nonce, $sPostData,$message);
        $status = $errCode != 0 ? "error" : "success";
        try {
            if (isset($message["InfoType"])) {
                if ($message["InfoType"] == "component_verify_ticket") {
                    Redis::setex("component_verify_ticket_".$message["AppId"],600,$message["ComponentVerifyTicket"]);
                    $status = "error";
                }
            } elseif (isset($message["Event"])) {
                $status = "success";
            }
        } catch (Exception $e) {
            Log::info("openClicent-------");
            Log::info(json_encode($message));
            Log::info($e);
            Log::info("openClicent-------");
            $status = "error";
        }
        return ["status"=>$status,"message"=>$message];
    }

    // 获取开发component_access_token
    public static function getComponentAccessToken($componentAppid)
    {
        $componentAccessToken = Redis::get("component_access_token_".$componentAppid);
        if (empty($componentAccessToken)) {
            $component_verify_ticket = Redis::get("component_verify_ticket_".$componentAppid);
            $config = Config::get("wechats.component_platform.".$componentAppid);
            $client = new Client;
            $params = ["component_appid"=>$componentAppid,"component_appsecret"=>$config["secret"],"component_verify_ticket"=>$component_verify_ticket];
            $response = $client->request('POST','https://api.weixin.qq.com/cgi-bin/component/api_component_token', [
                'body' => json_encode($params,JSON_UNESCAPED_UNICODE),
                'headers' => [
                    'Content-type'=> 'application/json',
                    'Accept'=>'application/json'
                ]]);

            $body = $response->getBody();
            $result = json_decode($body,true);
            if (!isset($result["component_access_token"])) {
                Log::info("getComponentAccessToken-------");
                Log::info(json_encode($result));
                Log::info("getComponentAccessToken-------");
                return "";
            }
            $componentAccessToken = $result["component_access_token"];
            Redis::setex("component_access_token_".$componentAppid,7100,$componentAccessToken);
        }
        return $componentAccessToken;
    }

    // 获取代小程序access_token
    public static function getMiniProgramAccessToken($componentAppid,$appId,$refreshToken)
    {
        $authorizerAccessToken = Redis::get("authorizer_access_token_".$componentAppid."_".$appId);
        if (empty($authorizerAccessToken)) {
            $component_verify_ticket = Redis::get($componentAppid);
            $config = Config::get("wechats.component_platform.".$componentAppid);
            $componentAccessToken = self::getComponentAccessToken($componentAppid);
            $client = new Client;
            $params = ["component_appid"=>$componentAppid,"authorizer_appid"=>$appId,"authorizer_refresh_token"=>$refreshToken];
            $response = $client->request('POST','https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$componentAccessToken, [
                'body' => json_encode($params,JSON_UNESCAPED_UNICODE),
                'headers' => [
                    'Content-type'=> 'application/json',
                    'Accept'=>'application/json'
                ]]);

            $body = $response->getBody();
            $result = json_decode($body,true);
            $authorizerAccessToken = $result["authorizer_access_token"];
            Redis::setex("authorizer_access_token_".$componentAppid."_".$appId,7200,$authorizerAccessToken);
        }
        return $authorizerAccessToken;
    }
}